package com.ocom.exposeapi.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.ExposeApiUrl;
import com.ocom.common.constant.MapKey;
import com.ocom.common.entity.card.EntityXfAccountInfo;
import com.ocom.common.entity.company.EntityComDockApi;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.company.GetReplyApiParaRequest;
import com.ocom.common.request.exposeapi.zr.ModifyPersonRequest;
import com.ocom.common.request.human.GetDeptIdByFullNameRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.utils.SignUtils;
import com.ocom.common.vo.PersonVo;
import com.ocom.common.vo.human.UserInfoVo;
import com.ocom.common.vo.human.UserInfoVo2;
import com.ocom.exposeapi.feign.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.SortedMap;

@Slf4j
@RestController
public class ZRController {

    @Autowired
    private CompanyClientService companyClientService;

    @Autowired
    private HumanFeignService humanFeignService;

    @Autowired
    private PayConfigClientService payConfigClientService;

    @Autowired
    private PayHandleClientService payHandleClientService;

    @Autowired
    private MqSimple mqSimple;

    @Autowired
    private XfRecordFeign xfRecordFeign;


    @PostMapping(ExposeApiUrl.URL_ExposeApi_zr_modifyPerson)
    public Result modifyPerson(@Validated @RequestBody ModifyPersonRequest request, BindingResult bindingResult) {
        log.info("中荣人员更新 【{}】【{}】【{}】",request.getPCode(),request.getPName(),request);
        String sign = request.getSign();
        request.setSign("");
        Result checkResult = checkSign(request.getComId(), "zr#modifyPerson", "zr", sign, JSON.toJSONString(request));
        if (200 != checkResult.getCode()) {
            return checkResult;
        }
        Long comId = Long.valueOf(checkResult.getData().toString());

        GetDeptIdByFullNameRequest getDeptIdByFullNameRequest = new GetDeptIdByFullNameRequest();
        getDeptIdByFullNameRequest.setComId(comId);
        getDeptIdByFullNameRequest.setDeptFullName(request.getDept());
        Result result = humanFeignService.getDeptIdByFullName(getDeptIdByFullNameRequest);
        if (200 != result.getCode()) {
            return result;
        }

        JSONObject deptJsonObject = JSON.parseObject(JSON.toJSONString(result.getData()));
        Long deptId = deptJsonObject.getLong("deptId");
        if (null == deptId) {
            deptId = 0l;
        }

        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setComId(comId);
        userInfoVo.setOnlyOne(true);
        userInfoVo.setPCode(request.getPCode());
        userInfoVo.setStatus(0);
        result = humanFeignService.PersonnelGetPersonInfo(userInfoVo);

        UserInfoVo2 userInfoVo2 = JSON.parseObject(JSON.toJSONString(result.getData()), UserInfoVo2.class);

            if (null == userInfoVo2) {
                PersonVo personVo = new PersonVo();
                personVo.setComId(comId);
                personVo.setPCode(request.getPCode());
                personVo.setPName(request.getPName());
                personVo.setDeptId(deptId);
                personVo.setPPhone(request.getPPhone());
                personVo.setPPhotoUrl(request.getPPhotoUrl());
                personVo.setStatus(0);
                result = humanFeignService.AddPerson(personVo);

                if (result.getCode() != 200) {
                    return result;
                }
                EntityPersonnelInfo entityPersonnelInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityPersonnelInfo.class);

                Map<String, Object> map = new HashMap<>();
                MapKey mapKey = new MapKey();
                if(ObjectUtil.isNotEmpty(entityPersonnelInfo)){
                    map.put(mapKey.getKey_pId(), entityPersonnelInfo.getPId());
                    map.put(mapKey.getKey_comId(), entityPersonnelInfo.getComId());
                    map.put(mapKey.getKey_accountNo(), entityPersonnelInfo.getComId() + "P" + entityPersonnelInfo.getPId());
                    map.put(mapKey.getKey_accountName(), entityPersonnelInfo.getComId() + "P" + entityPersonnelInfo.getPId());
                    map.put(mapKey.getKey_accountState(), 0);
                    map.put(mapKey.getKey_accTypeId(),request.getStatus());
                    result = payConfigClientService.AddXFAccount(map);//TODO
                }

            } else {

                Map<String, Object> map = new HashMap<>();
                MapKey mapKey = new MapKey();
                map.put(mapKey.getKey_comId(), comId);
                map.put(mapKey.getKey_deptId(), deptId);
                map.put(mapKey.getKey_pId(), userInfoVo2.getPId());
                map.put(mapKey.getKey_pCode(), request.getPCode());
                map.put(mapKey.getKey_pName(), request.getPName());
                map.put(mapKey.getKey_pPhone(), request.getPPhone());
                map.put(mapKey.getKey_pPhotoUrl(), request.getPPhotoUrl());
                map.put(mapKey.getKey_status(),0);
                result = humanFeignService.UpdatePerson(map);
                if (200 != result.getCode()) {
                    return result;
                }
                result = payConfigClientService.GetXFAccountByStatus(comId, userInfoVo2.getPId().intValue(),-1);
                if (200 != result.getCode()) {
                    return result;
                }
                    EntityXfAccountInfo entityXfAccountInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityXfAccountInfo.class);
                    if(ObjectUtil.isNotEmpty(entityXfAccountInfo)){
                            map = new HashMap<>();
                            map.put(mapKey.getKey_comId(), comId);
                            map.put(mapKey.getKey_id(), entityXfAccountInfo.getId());
                            map.put(mapKey.getKey_pId(), entityXfAccountInfo.getPId());
                            map.put(mapKey.getKey_accountState(), request.getStatus() == 8 ? 1 : 0);
                            map.put(mapKey.getKey_accTypeId(),request.getStatus());
                            result = payConfigClientService.UpdateXFAccount(map);
                    }
            }

        return result;
    }

    private Result checkSign(String comAppid, String dockApiCode,String dockCode, String requestSign, String requestJson) {
        GetReplyApiParaRequest getReplyApiParaRequest = new GetReplyApiParaRequest();
        getReplyApiParaRequest.setComAppid(comAppid);
        getReplyApiParaRequest.setDockCode(dockCode);
        getReplyApiParaRequest.setDockApiCode(dockApiCode);
        getReplyApiParaRequest.setKeyType(0);
        Result result = companyClientService.getReplyApiPara(getReplyApiParaRequest);
        if (result.getCode() == 200) {
            EntityComDockApi entityComDockApi = JSON.parseObject(JSON.toJSONString(result.getData()), EntityComDockApi.class);

            SortedMap<String, Object> parameters = JSON.parseObject(requestJson, SortedMap.class);
            String sign1 = SignUtils.createSign(parameters, entityComDockApi.getKey());
            log.info("当前签名【{}】", sign1);
            if (!requestSign.toLowerCase().equals(sign1)) {
                return ResultUtil.error(ResultEnum.Err_202);
            }
            result.setData(entityComDockApi.getComId());
        }
        return result;
    }
}
